<template>
  <div class="login">
    <el-form
      ref="loginformRef"
      label-position="top"
      :model="loginForm"
      label-width="80px"
      :rules="loginRules"
    >
      <h2>登录</h2>
      <el-form-item label="手机号" prop="phone">
        <el-input v-model="loginForm.phone"></el-input>
      </el-form-item>
      <el-form-item label="密码" prop="password">
        <el-input type="password" v-model="loginForm.password"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="onSubmit" :loading="isLoading"
          >登录</el-button
        >
      </el-form-item>
    </el-form>
  </div>
</template>
<script>
import { login } from '@/api/user'
export default {
  name: 'AppLogin',
  data () {
    return {
      // 表的数据
      loginForm: {
        phone: '18201288771',
        password: '111111'
      },
      // 请求中
      isLoading: false,
      // 验证规则
      loginRules: {
        phone: [
          { required: true, message: '手机号为必填', trigger: 'blur' },
          {
            pattern: /^1[3-9]\d{9}$/,
            message: '手机号不合法',
            trigger: 'blur'
          }
        ],
        password: [
          { required: true, message: '密码不能为空', trigger: 'blur' },
          { min: 3, max: 6, message: '密码长度不符合', trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    // 登录
    onSubmit () {
      this.isLoading = true
      this.$refs.loginformRef
        .validate()
        .then(() => {
          return login(this.loginForm)
        })
        .then(({ data }) => {
          if (data.success) {
            this.$message.success('登录成功')
            this.$store.commit('saveTokenInfo', data.content)
            this.$router.push(this.$route.query.redirect || '/')
          } else {
            this.$message.error('登录失败')
          }
        })
        .catch(() => {
          this.$message.error('表单验证失败')
        })
        .finally(() => {
          this.isLoading = false
        })
    }
  }
}
</script>
<style scoped lang="scss">
.login {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 100vh;
}

.el-form {
  width: 300px;
  background-color: #fff;
  padding: 30px;
  border-radius: 10px;

  .el-button {
    width: 100%;
  }
}
</style>
